<template>
  <div class="coaches-container">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="教练姓名">
          <el-input v-model="searchForm.name" placeholder="请输入教练姓名" clearable />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号码" clearable />
        </el-form-item>
        <el-form-item label="教练类型">
          <el-select v-model="searchForm.type" placeholder="请选择教练类型" clearable>
            <el-option label="科目二" value="科目二" />
            <el-option label="科目三" value="科目三" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>教练列表</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增教练
          </el-button>
        </div>
      </template>

      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="gender" label="性别" width="80" />
        <el-table-column prop="phone" label="手机号码" />
        <el-table-column prop="type" label="教练类型" />
        <el-table-column prop="experience" label="教龄(年)" width="100" />
        <el-table-column prop="studentCount" label="学员数" width="100" />
        <el-table-column prop="rating" label="评分" width="100">
          <template #default="{ row }">
            <el-rate v-model="row.rating" disabled text-color="#ff9900" />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '在职' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button type="success" link @click="handleViewSchedule(row)">
                <el-icon><Calendar /></el-icon>排班
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑抽屉 -->
    <el-drawer
      :title="dialogType === 'add' ? '新增教练' : '编辑教练'"
      v-model="dialogVisible"
      direction="rtl"
      size="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="教练类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择教练类型">
            <el-option label="科目二" value="科目二" />
            <el-option label="科目三" value="科目三" />
          </el-select>
        </el-form-item>
        <el-form-item label="教龄" prop="experience">
          <el-input-number v-model="form.experience" :min="0" :max="50" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="在职">在职</el-radio>
            <el-radio label="离职">离职</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 排班抽屉 -->
    <el-drawer
      title="教练排班"
      v-model="scheduleDialogVisible"
      direction="rtl"
      size="60%"
    >
      <el-calendar v-model="currentDate">
        <template #dateCell="{ data }">
          <div class="calendar-cell">
            <p>{{ data.day.split('-').slice(1).join('-') }}</p>
            <el-tag
              v-if="getScheduleStatus(data)"
              :type="getScheduleStatus(data) === '可预约' ? 'success' : 'danger'"
              size="small"
            >
              {{ getScheduleStatus(data) }}
            </el-tag>
          </div>
        </template>
      </el-calendar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="scheduleDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleSaveSchedule">保存排班</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Edit,
  Delete,
  Calendar
} from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  name: '',
  phone: '',
  type: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([
  {
    name: '李教练',
    gender: '男',
    phone: '13800138001',
    type: '科目二',
    experience: 5,
    studentCount: 20,
    rating: 4.5,
    status: '在职'
  }
])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 表单
const dialogVisible = ref(false)
console.log('dialogVisible initialized:', dialogVisible)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  name: '',
  gender: '男',
  phone: '',
  type: '',
  experience: 0,
  status: '在职'
})

// 排班相关
const scheduleDialogVisible = ref(false)
const currentDate = ref(new Date())

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  type: [{ required: true, message: '请选择教练类型', trigger: 'change' }],
  experience: [{ required: true, message: '请输入教龄', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 搜索
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  console.log('search:', searchForm)
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  Object.keys(form).forEach(key => {
    form[key] = key === 'gender' ? '男' : key === 'status' ? '在职' : key === 'experience' ? 0 : ''
  })
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该教练信息吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // TODO: 实现删除逻辑
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 查看排班
const handleViewSchedule = (row) => {
  scheduleDialogVisible.value = true
}

// 获取排班状态
const getScheduleStatus = (data) => {
  // TODO: 根据实际排班数据返回状态
  return Math.random() > 0.5 ? '可预约' : '已约满'
}

// 保存排班
const handleSaveSchedule = () => {
  // TODO: 实现保存排班逻辑
  ElMessage.success('排班保存成功')
  scheduleDialogVisible.value = false
}

// 提交表单
const handleSubmit = async () => {
  console.log('handleSubmit called, dialogVisible:', dialogVisible)
  if (!formRef.value) return
  await formRef.value.validate((valid) => {
    if (valid) {
      // 实现提交逻辑
      if (dialogType.value === 'add') {
        // 模拟新增教练
        const newCoach = {
          ...form,
          studentCount: 0,
          rating: 5,
          id: Date.now()
        }
        tableData.value.unshift(newCoach)
        total.value++
      } else {
        // 模拟修改教练
        const index = tableData.value.findIndex(item => item.id === form.id)
        if (index !== -1) {
          tableData.value[index] = {...form}
        }
      }
      console.log('submit:', form)
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
      dialogVisible.value = false
    }
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}
</script>

<style scoped>
.coaches-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.calendar-cell {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.calendar-cell p {
  margin: 0;
  line-height: 1;
}
</style>